package com.tongyi.lizhishop.activitys;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.tongyi.lizhishop.R;
import com.tongyi.lizhishop.api.StoreApi;
import com.tongyi.lizhishop.beans.CommonResonseBean;
import com.tongyi.lizhishop.beans.StoreBean;
import com.tongyi.lizhishop.beans.StoreTypeBean;
import com.tongyi.lizhishop.common.BaseActivity;
import com.tongyi.lizhishop.common.CommonObserver;
import com.tongyi.lizhishop.managers.APIServiceManager;
import com.tongyi.lizhishop.utils.PromptDialogUtils;
import com.wuhenzhizao.titlebar.widget.CommonTitleBar;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.leefeng.promptlibrary.PromptDialog;

import static com.tongyi.lizhishop.R.id.choose1ll;

public class StoreTypeActivity extends BaseActivity {

    @BindView(R.id.titlebar)
    CommonTitleBar titlebar;
    @BindView(R.id.choose1Tv)
    TextView choose1;
    @BindView(R.id.choose2Tv)
    TextView choose2;
    @BindView(R.id.confirm)
    Button confirm;
    @BindView(R.id.activity_store_manager)
    LinearLayout activityStoreManager;
    @BindView(R.id.tvContainer)
    LinearLayout tvContainer;
    private List<StoreTypeBean.ArrayBean> options1Items = new ArrayList();
    private List<StoreTypeBean.ArrayBean> options2Items = new ArrayList();
    private PromptDialog prompDialog;
    int option1Index = -1;
    int option2Index = -1;
    String sel_merid1;
    String sel_merid2;
    private boolean hasShow = false;
    private boolean isSubmit = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_store_type);
        ButterKnife.bind(this);
        initTitleBarView(titlebar, "店铺分类");
        prompDialog = PromptDialogUtils.getPrompDialog(this);
        loadData();
    }

    private void loadData() {
        prompDialog.showLoading("请等待");
        APIServiceManager.getInstance().create(StoreApi.class)
                .infoSeller(SPUtils.getInstance().getString("userid"))
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new CommonObserver<StoreBean>() {
                    @Override
                    public void onSuccess(StoreBean value) {
                        prompDialog.dismissImmediately();
                        choose1.setText(value.getArray().getMername1());
                        choose2.setText(value.getArray().getMername2());
                        sel_merid1 = value.getArray().getSel_merid1();
                        sel_merid2 = value.getArray().getSel_merid2();
                    }

                    @Override
                    public void onFailure(Throwable e) {
                        prompDialog.dismissImmediately();
                        ToastUtils.showShort("请求数据失败!请检查网络");

                    }
                });
    }


    @OnClick({choose1ll, R.id.choose2ll, R.id.confirm})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case choose1ll:
                loadData("0", choose1, options1Items);
                break;
            case R.id.choose2ll:
                StoreTypeBean.ArrayBean tag = (StoreTypeBean.ArrayBean) choose1.getTag();
                if (tag == null) {
                    if (TextUtils.isEmpty(sel_merid1)) {
                        ToastUtils.showShort("请先选择第一项");
                    } else {
                        loadData(sel_merid1, choose2, options2Items);
                    }
                } else {
                    String mer_id = tag.getMer_id();
                    loadData(mer_id, choose2, options2Items);
                }

                break;
            case R.id.confirm:
                Object tag1 = choose1.getTag();
                Object tag2 = choose2.getTag();


                if ("请选择".equals(choose1.getText()) || "请选择".equals(choose2.getText())) {
                    ToastUtils.showShort("请先选择店铺分类");
                    return;
                }


                StoreTypeBean.ArrayBean tag11 = (StoreTypeBean.ArrayBean) tag1;
                StoreTypeBean.ArrayBean tag22 = (StoreTypeBean.ArrayBean) tag2;

                String mer_id;
                if (tag11 != null) {
                    mer_id = tag11.getMer_id();
                } else {
                    mer_id = sel_merid1;
                }

                String mer_id1;

                if (tag22 != null) {
                    mer_id1 = tag22.getMer_id();
                } else {
                    mer_id1 = sel_merid2;
                }
                uploadStoreType(mer_id, mer_id1);
                break;
        }
    }

    private void uploadStoreType(final String mer_id1, final String merId2) {
        prompDialog.showLoading("请等待", false);
        APIServiceManager.getInstance().create(StoreApi.class)
                .saveMerchanttype(SPUtils.getInstance().getString("userid"), mer_id1, merId2)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new CommonObserver<CommonResonseBean>() {
                    @Override
                    public void onSuccess(CommonResonseBean value) {
                        prompDialog.showSuccess("保存成功", false);
                        LogUtils.w(value);
                        ToastUtils.showShort("保存成功");
                        SPUtils.getInstance().put("sel_merid1", Integer.parseInt(mer_id1));
                        isSubmit = true;
                        SPUtils.getInstance().put("sel_merid2", Integer.parseInt(merId2));
                        Intent data = new Intent();
                        data.putExtra("status", 1);
                        setResult(RESULT_OK, data);
                        finish();
                    }

                    @Override
                    public void onFailure(Throwable e) {
                        prompDialog.showError("保存失败请重试", false);
                        e.printStackTrace();
                    }
                });
    }

    private void loadData(String fid, final TextView textView, final List list) {
        prompDialog.showLoading("请等待", false);
        APIServiceManager.getInstance().create(StoreApi.class)
                .Merchanttype(fid)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new CommonObserver<StoreTypeBean>() {
                    @Override
                    public void onSuccess(StoreTypeBean value) {
                        prompDialog.dismissImmediately();
                        List<StoreTypeBean.ArrayBean> array = value.getArray();
                        list.clear();
                        list.addAll(array);
                        if (list.size() == 0) {
                            ToastUtils.showShort("服务返回的数据为空!");
                            return;
                        }
                        showPick(list, textView);
                        LogUtils.w(value);

                    }

                    @Override
                    public void onFailure(Throwable e) {
                        e.printStackTrace();
                        prompDialog.showError("无法连接网络");
                        ToastUtils.showShort("无法连接网络!");
                    }
                });
    }

    private void showPick(final List<StoreTypeBean.ArrayBean> list, final TextView tv) {
        final ArrayList<String> localItems = new ArrayList<>();
        for (StoreTypeBean.ArrayBean bean : list) {
            localItems.add(bean.getMer_name());
        }
        //条件选择器
        OptionsPickerView pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                tv.setText(localItems.get(options1).toString());
                tv.setCompoundDrawables(null, null, null, null);
                Object lastTag = tv.getTag();
                StoreTypeBean.ArrayBean currentTag = list.get(options1);
                tv.setTag(currentTag);

                if ((lastTag == null ||
                        !((StoreTypeBean.ArrayBean) lastTag).getMer_id().equals(currentTag.getMer_id()))
                        && tv == choose1) {
                    //第一项又重新选择了
                    //清除第二项选择的内容;
                    choose2.setTag(null);
                    choose2.setText("请选择");
                }

            }
        }).build();
        pvOptions.setPicker(localItems);
        pvOptions.show();

    }

 /*   private TextView createTextView() {

        TextView textView = new TextView(this);
        textView.setGravity(Gravity.CENTER);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        int margins = SizeUtils.dp2px(16);
        params.setMargins(margins, margins, margins, margins);
        textView.setLayoutParams(params);
        textView.setBackground(getResources().getDrawable(R.drawable.shape_edit_bg_rectang));
        textView.setTextSize(16);
        textView.setTextColor(getResources().getColor(R.color.mainTextColor));
        int dimension = (int) getResources().getDimension(R.dimen.margin10dp);
        textView.setPadding(dimension, dimension, dimension, dimension);
        textView.setText("请选择");
        return textView;
    }*/

}
